package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
        @Autowired
        private OrdersMapper ordersMapper;
        @Scheduled(cron = "*/5 * * * * *")//每隔五秒触发一次
        public void outTimeOrder(){
            log.info("开始检查过期订单{}",LocalDateTime.now());
            //查找未支付并且已经超时15分钟的订单
            Integer status = Orders.PENDING_PAYMENT;
            LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
            List<Orders> ordersList = ordersMapper.getStatusAndTime(status, time);
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED); //修改订单状态为取消状态
                orders.setCancelTime(LocalDateTime.now());//修改取消时间
                orders.setCancelReason("订单超时，自动取消");
                ordersMapper.update(orders);

            }
        }
        //@Scheduled(cron = "0 0 1 * * *") //每天的凌晨一点触发 自动完成订单
        @Scheduled(cron = "*/5 * * * * *")//每隔五秒触发一次
        public void completeOrder(){
            log.info("开始自动完成订单{}",LocalDateTime.now());
                //查找 派送中 并且时间为昨天的订单
            Integer status = Orders.DELIVERY_IN_PROGRESS;
            LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
            List<Orders> ordersList = ordersMapper.getStatusAndTime(status, time);
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED); //修改订单状态为完成状态
                ordersMapper.update(orders);

            }
        }
}
